﻿<%@ Page Title="角色管理" Language="C#" MasterPageFile="~/master/m.master" %>
<script runat="server"></script>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<link href="../assets/css/plugins/jsTree/style.min.css" rel="stylesheet">
<link href="../assets/css/plugins/footable/footable.core.css" rel="stylesheet">
<link href="../assets/css/plugins/iCheck/custom.css" rel="stylesheet">
<link href="../assets/img/validate/validate.css" rel="stylesheet">
<link rel="stylesheet" href="../assets/css/bootstrap.min.css">
<style type="text/css">
#roleList{
	overflow: auto; 
	width: auto;
}
	
.list-group-item{
	padding: 4px 10px;
	white-space:nowrap;
	min-width: 220px;
}
		
.pageControl{
	position: fixed;
	background: #fff;
	right: 0;
	bottom: 0;
	width: calc(100% - 220px);
}
	
#configWindow .nav>li.active>a{
	color: #a7b1c2;
}
#configWindow .nav>li.active>a:hover{
	color: #676a6c;
}
#configWindow .tabs-container .tab-content>.active{
	display: block;
}

.roleInfo{
	padding-bottom: 5px;
}
.roleInfo span{
	display: inline-block;
	margin-right: 20px;
	color: #999;
}
.roleType:before,
.roleDept:before,
.roleCount:before,
.roleOrder:before,
.roleState:before{
	color: #222;
	font-weight: bold;
}
.roleType:before{
	content: "角色分类：";
}
.roleDept:before{
	content: "所属部门：";
}
.roleCount:before{
	content: "人数：";
}
.roleOrder:before{
	content: "排序：";
}
.roleState:before{
	content: "状态：";
}
	
.tabs-container .panel-body{
	padding: 5px;
}
	
.roleInfoUsers, .roleInfoModules{
	height: 250px;
	width: 100%;
}
.roleInfoUsers{
	overflow-y: auto;
}
.roleInfoModules{
	overflow-y: hidden;
}
.moduleHead th, .moduleBody td{
	display: inline-block!important;
	border: 0!important;
	vertical-align: middle;
	text-align: center;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

@media (min-width: 768px) {
	.modal-dialog {
		width: 768px;
		margin: 30px auto;
	}
}
.moduleHead thead{
  display: none;
}
 #tab-2 .panel-body .roleInfoModules .moduleBody tbody tr td{
    width: 80px ;

}
#tab-2 .panel-body .roleInfoModules .moduleBody tbody tr td:nth-child(1){
    width: 130px
}
#thName{
    padding-left:30px; 
     color: black;
}
#thBtn{
    padding-left: 66px ;
    color: black;
    
}
.moduleBody thead{
    background: gray;
    opacity: .8
}
.moduleBody {
    border: 1px solid gray;
}
#moduleHead-T{
  position: absolute;
  left: 0;
  top: 0;
}
#moduleHead-C{
  position: relative;

}
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="main" Runat="Server">
	<div class="system-box">
		<div class="left-side  ibox-content">
			<div id="using_json"></div>
		</div>
		<div class="right-side">
			<div class="btns-container">
				<div class="modal inmodal" id="addWindow" tabindex="-1" role="dialog" aria-hidden="true">
					<form id="checkModuleForm" method="get" action="#">
						<div class="modal-dialog">
							<div class="modal-content animated bounceInRight">
								<div class="modal-header">
									<span class="editTitle">新增角色</span>
									<button type="button" class="close" data-dismiss="modal">
										<span aria-hidden="true">&times;</span>
										<span class="sr-only">关闭</span>
                                	</button>
								</div>
								<div id="message" style="display: none"></div>
								<div class="modal-body">
									<table class="module-info" cellpadding="0" cellspacing="0">
										<thead></thead>
										<tbody>
											<tr>
												<td>
													<div class="form-group">
	                                					<label class="control-label">角色名称&nbsp;&nbsp;</label>
	                                					<input id="RoleName" name="RoleName" placeholder="请输入角色名称" 
	                                						datacol="yes" err="角色名称" checkexpession="NotNull"
	                                						maxlength="10" type="text" class="form-control input-w288 required" />
	                            					</div>
												</td>
												<td>
													<div class="form-group">
	                                					<label class="control-label">显示顺序&nbsp;&nbsp;</label>
	                                					<input id="Sort" name="Sort" maxlength="3" type="number" class="form-control input-w288" />
	                            					</div>
												</td>
											</tr>
											<tr>
												<td>
													<div class="form-group">
                                						<label class="control-label">角色分类&nbsp;&nbsp;</label>
	                                    				<select class="form-control m-b input-w288" id="RoleType" name="RoleType"
                                                            datacol="yes" err="角色分类" checkexpession="NotNull">
                                                            <option value="9">系统管理员</option>
	                                        				<option value="1">系统角色</option>
	                                        				<option value="2">业务角色</option>
                                                            <option value="3">修改数据角色</option>
	                                    				</select>
                            						</div>
												</td>
												<td style="vertical-align: baseline;">
													<label class="control-label">是否有效&nbsp;&nbsp;</label>
													<div class="checkbox i-checks label-inline">
														<label class="effective">
															<input id="IsEffective" type="checkbox" checked="">
														</label>
		                                        	</div>
												</td>
											</tr>
											<tr>
												<td colspan="2">
													<label class="control-label label-float">备注说明&nbsp;&nbsp;</label>
													<textarea id="Memo" name="Memo" placeholder="在此输入备注说明" 
														style="margin-left: 3px;" class="form-control input-textarea input-w660"></textarea>
												</td>
											</tr>
										</tbody>
									</table>
								</div>
								<div class="modal-footer">
									<button type="button" id="addModuleBtn" class="btn btn-primary">保存</button>
									<button type="button" id="closeAddBox" class="btn btn-white" data-dismiss="modal">关闭</button>
								</div>
							</div>
						</div>
					</form>
				</div>
								
				<div class="modal inmodal" id="roleUserWindow" tabindex="-1" role="dialog" aria-hidden="true">
					<div class="modal-dialog">
						<div class="modal-content animated bounceInRight">
							<div class="modal-header">
								<span>角色用户</span>
								<button type="button" class="close" data-dismiss="modal">
									<span aria-hidden="true">&times;</span>
									<span class="sr-only">关闭</span>
                                </button>
							</div>
							<div class="modal-body" style="padding: 0;">
								<div class="tips">
									<i class="fa fa-lightbulb-o"></i>
									温馨提示：点击模块中的多选框，可以同时保存多个模块的按钮配置,而且保存时，至少要选中一个
								</div>
								<div class="btn-config-box">
									<div class="box-title">
										<div class="left-side">部门列表</div>
										<div class="right-side">
											<span class="right-side-title">当前角色：</span><span class="chooseRole"></span>
											<input id="searchText" placeholder="用户查询" style="line-height: 20px;" />
											<button type="button" id="chooseAllUser" style="float: right; margin: 3px 2px 0 0; height: 24px; line-height: 10px; font-size: 12px;" class="btn btn-success">全选</button>
										</div>
									</div>
									<div style="float: left; width: 220px; overflow: auto;">
										<div class="btn-config-tree" id="roleList">
										
										</div>
									</div>
									<div class="btn-config-list" id="userList">
										<div class="searchList">
											
										</div>
									</div>
								</div>
							</div>
							<div class="modal-footer">
								<button type="button" id="saveRoleConfig" class="btn btn-primary">保存</button>
								<button type="button" class="btn btn-white closeBtn" data-dismiss="modal">关闭</button>
							</div>
						</div>
					</div>
				</div>
				
				<div class="modal inmodal" id="roleLimitWindow" tabindex="-1" role="dialog" aria-hidden="true">
					<div class="modal-dialog">
						<div class="modal-content animated bounceInRight">
							<div class="modal-header">
								<span>角色权限</span>
								<button type="button" class="close" data-dismiss="modal">
									<span aria-hidden="true">&times;</span>
									<span class="sr-only">关闭</span>
                                </button>
							</div>
							<div class="modal-body" style="padding: 0;">
								<div class="tips">
									<i class="fa fa-lightbulb-o"></i>
									温馨提示：点击模块中的多选框，可以同时保存多个模块的按钮配置,而且保存时，至少要选中一个
								</div>
								<div class="btn-config-box">
									<div class="box-title">
										<div class="left-side">模块列表</div>
										<div class="right-side">
											<span class="right-side-title">当前模块：</span><span class="chooseModule"></span>
											<button type="button" id="chooseAllLimit" 
												style="float: right; margin: 3px 2px 0 0; height: 24px; line-height: 10px; font-size: 12px;"
												class="btn btn-success">全选</button>
										</div>
									</div>
                                    
									<div class="btn-config-tree" id="moduleList">
										
									</div>
									<div class="btn-config-list" id="btnList">

									</div>
								</div>
							</div>
							<div class="modal-footer">
								<button type="button" id="saveModuleConfig" class="btn btn-primary">保存</button>
								<button type="button" class="btn btn-white closeBtn" data-dismiss="modal">关闭</button>
							</div>
						</div>
					</div>
				</div>
				
				<div class="modal inmodal" id="configWindow" tabindex="-1" role="dialog" aria-hidden="true">
					<div class="modal-dialog" style="width: 950px;">
						<div class="modal-content animated bounceInRight">
							<div class="modal-header">
								<span class="showRoleTitle">查看角色</span>
								<button type="button" class="close" data-dismiss="modal">
									<span aria-hidden="true">&times;</span>
									<span class="sr-only">关闭</span>
                                </button>
							</div>
							<div class="modal-body" style="padding: 5px; border-radius: 0 0 3px 3px;">
								<div class="roleInfo">
									<span class="roleType"></span>
									<span class="roleDept"></span>
									<span class="roleCount"></span>
									<!--<span class="roleOrder"></span>-->
									<span class="roleState"></span>
								</div>
								<div class="tabs-container">
									<ul class="nav nav-tabs">
                        				<li class="active">
                        					<a data-toggle="tab" href="#tab-1" aria-expanded="true">用户信息</a>
                        				</li>
	                        			<li class="">
	                        				<a data-toggle="tab" href="#tab-2" aria-expanded="false">模块权限</a>
	                        			</li>
                    				</ul>
                    				<div class="tab-content">
				                        <div id="tab-1" class="tab-pane active">
				                            <div class="panel-body">
				                            	<div class="roleInfoUsers">
				                            		
				                            	</div>
				                            </div>
				                        </div>
				                        <div id="tab-2" class="tab-pane">
				                            <div class="panel-body">
				                            	<div class="roleInfoModules" id="moduleHead-C">
				                            		<table class="footable table table-stripped table-list moduleHead" >
				                            			<thead></thead>
				                            			<tbody></tbody>
				                            		</table>
				                            		<div style="width: 100%; overflow-y: scroll; height: 226px;" id="moduleHead-T">
				                            			<table class="footable table table-stripped table-list moduleBody" border-color="gray" border="1" cellspacing="0" cellpadding="0">
					                            			<thead>
                                                                <tr>
                                                                    <td id="thName">模块名称</td>
                                                                    <td id="thBtn">按钮权限</td>
                                                                </tr>
                                                            </thead>
					                            			<tbody></tbody>
					                            		</table>
				                            		</div>
				                            	</div>
				                            </div>
				                        </div>
                    				</div>
								</div>
								
							</div>
						</div>
					</div>
				</div>
				
			</div>
			
			<div class="right-content-box">
				<div class="ibox-content">
					<table class="footable table table-stripped table-list roleTable">
						<thead></thead>
						<tbody id="pageList"></tbody>
					</table>
                </div>
			</div>
             
			<div class="pageControl"></div>
		</div>
	</div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="footer" Runat="Server">
<script src="../assets/js/plugins/jsTree/jstree.min.js"></script>
<script src="../assets/js/plugins/footable/footable.all.min.js"></script>
<script src="../assets/js/plugins/treeview/bootstrap-treeview.js"></script>
<script src="../assets/js/plugins/iCheck/icheck.min.js"></script>
<script src="../assets/js/page/pageControl.js"></script>
<script src="../assets/js/page/dept.js"></script>
<script src="../assets/js/lodash.js"></script>
<script src="../assets/js/page/rScroll.js"></script>
<script src="../assets/js/page/tableControl.js"></script>
<script src="../assets/img/validate/learunui-validator.js"></script>
<script type="application/javascript">
$(document).ready(function () {
    //初始化多选框
    $(".i-checks").iCheck({
        checkboxClass: "icheckbox_square-green",
    });

    //用于记录当前选中节点id（部门id）
    var deptId = 1;
    //用于记录当前选中节点grade
    var deptGrade = 1;
    //用于给予当前选中节点父id
    var deptParent = 0;
    //用于标记是新增还是编辑
    var isCreate = true;
    //用于记录角色id
    var rid = -1;
    //用于记录当前页数
    var page = 1;
    //用于记录每页多少条记录
    var size = 10; 
    //获取按钮配置
    var btnStyleJson = [];
    commonUtil.getJson('../assets/json/btnConfig.json', {}, function (data) {
        btnStyleJson = data.styles;
    });
    //用于记录角色权限集合
    var roleLimitList = [];
    var tempLimitList = [];
    //用于记录当前选中的模块id
    var mid = 1;
    //用于处理部门列表json
    var deptData = {};
    var deptTree = [];

	//模块ID
	var ModuleID = Y.getUrlParam("ModuleID");
	//获取按钮
	commonUtil.loadBtnList(ModuleID,function(){
		rScroll();
	});

	var loginJson = window.sessionStorage.getItem('login-info');
	var btnStyle = 'btn-Style1';
	if(!Y.checkNull(loginJson)){
		loginJson = JSON.parse(loginJson);
		loginJson.ConfigList.map(function(item){
			if(item.dictValue == 'btn-Style')
				btnStyle = item.Value;
		})
	}

    //加载导航列表
    var loadList = function (init) {
        //调用加载层
        layer.msg('玩命加载中……', {icon: 16, shade: 0.5, time:0, maxWidth:200});
        Y.API2('Dept', 'GetList', { DeptCode: 1 }, function (data) {
            //关闭加载层
            layer.closeAll('dialog');

            var treeData = {};
            if (!Y.checkNull(data) && data.length > 0) {
                //json处理
                data.map(function (item, i) {
                    treeData.text = item.DeptContent;
                    treeData.data = {
                        Grade: item.Grade,
                        DeptID: item.DeptID,
                        ParentID: item.ParentID,
                    };
                    deptData = treeData;
                    if (item.Children.length > 0) {
                        treeData.state = { opened: true };
                        treeData.children = deptUtils.getChildNode(item.Children);
                        deptData.nodes = getDeptNode(item.Children);
                    }
                })
                // console.log(treeData)
                //初始化左侧菜单
                $.jstree.destroy("#using_json");
                $('#using_json').jstree({
                    core: {
                        data: [treeData]
                    }
                }).bind('select_node.jstree', function (event, data) {
                   // 绑定的点击事件
                    var node_data = data.node.data;
                    deptId = node_data.DeptID;
                    deptGrade = node_data.Grade;
                    deptParent = node_data.ParentID;

					page = 1;
                    //加载右侧列表
                    loadPageList(deptId, true);
                });

                //判断是否为初次调用
                if (!Y.checkNull(init)) {
                    //获取初始化的相关属性
                    deptId = data[0]['DeptID'];
                    deptGrade = data[0]['Grade'];
                    deptParent = data[0]['ParentID'];
                    //加载右侧列表
                    loadPageList(deptId, true);

                    deptTree.push(deptData);
                }
            }
        });
    }
    loadList(true);

    //加载用户按钮
    var loadUsers = function (data) {
        var html = '';
        data.map(function (item, i) {
            html += '<div class="btn-container">';
            html += '<button type="button" class="btn '+ (btnStyle == 'btn-Style1' ? '' : 'btn-outline ') +'btn-' + (item.Sex ? 'success' : 'danger') + '">';
            html += '<i class="fa fa-' + (item.Sex ? 'mars' : 'venus') + '"></i>';
            html += '<input type="hidden" class="bid" value="' + item.UsersID + '" />&nbsp;&nbsp;' + item.UserName;
            html += '</button>';
            html += '<div class="ischeck">';
            html += '<i class="fa fa-check '+ (btnStyle == 'btn-Style1' ? '' : (item.Sex ? 'text-success' : 'text-danger')) +'"></i>';
            html += '</div>';
            html += '</div>';
        });
        return html;
    }

    //搜索用户
    var searchUsers = function (did) {
        $('#userList .searchList').empty();
        Y.API2('Users', 'GetUserMo', { DeptID: did, UserName: $('#searchText').val() }, function (data) {
            if (data.Success == false) {
                swal(data.Message, '', 'error');
            } else {
                var tempData = [];
                data.map(function (item, i) {
                    var count = 0;
                    $('#userList .oldList .btn-container').each(function () {
                        if (item.UsersID == parseInt($(this).find('.bid').val())) {
                            return false;
                        }
                        count++;
                    });
                    if (count == $('#userList .oldList .btn-container').size()) {
                        tempData.push(item);
                    }
                });
                $('#userList .searchList').append(loadUsers(tempData));

                $('#userList .searchList .btn-container').each(function () {
                    var $this = $(this);
                    roleUserIds.map(function (item) {
                        if (item == parseInt($this.find('.bid').val())) {
                            $this.addClass('check');
                        }
                    })
                });
            }
        });
    }

    //初始化角色用户
    var did;
    var roleUserIds = [];
    var initRoleList = function (data) {
        $('#roleList').treeview({
            data: deptTree,
        }).on('nodeSelected', function (event, d) {
            //选择节点事件
            did = d.data.DeptID;
            searchUsers(did);
        });
        roleUserIds = [];
        data.map(function(item){
            roleUserIds.push(item.UsersID);
        });
        $('#roleList').treeview('selectNode', [0]);
    }

    //输入搜索（角色用户）
    var searchText = document.getElementById('searchText');
    searchText.addEventListener('input', function () {
        searchUsers(did);
    }, false);

    //选择用户（角色用户）
    $('#userList').on('click', '.btn-container', function () {
        if ($(this).hasClass('check')) {
            $(this).removeClass('check');
            if ($(this).parent().hasClass('searchList')) {
                _.pull(roleUserIds, parseInt($(this).find('.bid').val()));
            }
        } else {
            $(this).addClass('check');
            if ($(this).parent().hasClass('searchList')) {
                roleUserIds.push(parseInt($(this).find('.bid').val()));
            }
        }
    })

    //全选（角色用户）
    $('#chooseAllUser').click(function () {
        if ($('#userList .btn-container').size() == $('#userList .btn-container.check').size()) {
            $('#userList .btn-container').removeClass('check');
            $('#userList .searchList .btn-container').each(function () {
                var $this = $(this);
                roleUserIds.map(function (item) {
                    if (item == parseInt($this.find('.bid').val())) {
                        _.pull(roleUserIds, item);
                    }
                })
            });
        } else {
            $('#userList .btn-container').addClass('check');
            $('#userList .searchList .btn-container').each(function () {
                var count = 0;
                var $this = $(this);
                roleUserIds.map(function (item) {
                    if (item == parseInt($this.find('.bid').val())) {
                        return false;
                    }
                    count++;
                })
                if (count == roleUserIds.length) {
                    roleUserIds.push(parseInt($(this).find('.bid').val()));
                }
            });
        }
    });

    //加载按钮列表
    var loadBtnList = function (moduleID) {
        Y.API2('Button', 'GetSetButtonList', { moduleId: moduleID }, function (data) {
            if (data.Success == false) {
                swal(data.Message, '', 'error');
            } else {
                var html = '';
                data.map(function (item, i) {
                    html += '<div class="btn-container">';
                    html += '<button type="button" class="btn ' + (btnStyle == 'btn-Style1' ? '' : 'btn-outline ') + item.BackColor + '">';
                    html += '<input type="hidden" class="bid" value="' + item.ID + '" />';
                    if(!Y.checkNull(item.Icon) && btnStyle == 'btn-Style1'){
						html += '<i class="' + item.Icon + '"></i>&nbsp;&nbsp;' + item.BtnName;
					}else{
						html += item.BtnName;
					}
                    html += '</button>';
                    html += '<div class="ischeck">';
                    html += '<i class="fa fa-check '+ (btnStyle == 'btn-Style1' ? '' : item.BackColor.replace('btn','text')) +'"></i>';
                    html += '</div>';
                    html += '</div>';
                });
                $('#btnList').append(html);

                var count = 0;
                tempLimitList.map(function (item, i) {
                    if (mid == item.ModuleID) {
                        item.BtnID.map(function (bitem, j) {
                            $('#btnList .btn-container').each(function () {
                                if (parseInt($(this).find('.bid').val()) == bitem) {
                                    $(this).addClass('check');
                                }
                            })
                        });
                        return false;
                    }
                    count++;
                })

                if (count == tempLimitList.length) {
                    tempLimitList.push({
                        ModuleID: mid,
                        BtnID: []
                    })
                }
                
            }
        });
    }

    //选择权限
    $('#btnList').on('click', '.btn-container', function () {
        //处理样式
        if ($(this).hasClass('check')) {
            $(this).removeClass('check');
        } else {
            $(this).addClass('check');
        }
        //储存按钮id
        tempLimitList.map(function (item, i) {
            if (item.ModuleID == mid) {
                item.BtnID = [];
                $('#btnList .btn-container').each(function () {
                    if ($(this).hasClass('check')) {
                        item.BtnID.push(parseInt($(this).find('.bid').val()));
                    }
                })
            }
        })
    });
    //全选（角色权限）
    $('#chooseAllLimit').on('click', function () {
        if ($('#btnList .btn-container').size() == $('#btnList .btn-container.check').size()) {
            $('#btnList .btn-container').removeClass('check');
        } else {
            $('#btnList .btn-container').addClass('check');
        }
        //储存按钮id
        tempLimitList.map(function (item, i) {
            if (item.ModuleID == mid) {
                item.BtnID = [];
                $('#btnList .btn-container').each(function () {
                    if ($(this).hasClass('check')) {
                        item.BtnID.push(parseInt($(this).find('.bid').val()));
                    }
                })
            }
        })
    });

    //获取右侧内容列表
    var loadPageList = function (deptId, needLayer) {       	
    	if($('.roleTable thead').children().size() == 0)
    		tableControl.initThead2('.roleTable',['编号','角色名称','角色分类','所属部门','人数','排序','状态']);
			
    	pageControl.init('Role','GetList',{
			DeptID: deptId,
            Page: page,
//	                Size: size,
			needLayer: needLayer,
			alwaysCallBack:function(){
				rid = -1;
                $('#editBtn').attr('disabled', 'disabled');
                $('#deleteBtn').attr('disabled', 'disabled');
                $('#roleUserBtn').attr('disabled', 'disabled');
                $('#roleLimitBtn').attr('disabled', 'disabled');
                $('#examineBtn').attr('disabled', 'disabled');
			}
		},function(result){					
			page = result.page;
			var tBody = [];
			if (!Y.checkNull(result.data)) {
				if (result.data.Items.length > 0){					
			    	result.data.Items.map(function(item,i){             		
						var tempTr = {
							trClass: (i % 2 == 0 ? 'gradeX footable-even' : 'gradeX footable-odd' ),
							children: [
								{tdText: item.ID, c:0 , r:0, tdHtml:'', tdId:'', tdClass:''},
								{tdText: (item.RoleName || ' '), c:0 , r:0, tdHtml:'', tdId:'', tdClass:''},
								{tdText: (item.RoleType == 1 ? '系统角色': '业务角色'), c:0 , r:0, tdHtml:'', tdId:'', tdClass:''},
								{tdText: (item.DeptName || ' '), c:0 , r:0, tdHtml:'', tdId:'', tdClass:''},
								{tdText: item.UserCount, c:0 , r:0, tdHtml:'', tdId:'', tdClass:''},
								{tdText: item.Sort, c:0 , r:0, tdHtml:'', tdId:'', tdClass:''},
								{tdText: (item.IsEffective ? ' 有效 ' : ' 无效 '), c:0 , r:0, tdHtml: ('<i class="fa fa-'+ (item.IsEffective ? 'check text-navy' : 'times text-danger') +'"></i>'), tdId:'', tdClass:''},
							]
						};
						tBody.push(tempTr);
					})
			   	}
			   	rScroll();
			}
			tableControl.initTbody('.roleTable',(tBody.length > 0 ? tBody : null),6,null);
		});
    }
    var loadIndex = function () {
        Y.API2('Common', 'GetSort', { "tableName": "sys_role", "sortName": "sort" }, function (data) {
            if (data.Success == false) {
                //layer.msg(data.Message);
            } else {
                $("#Sort").val(data + 1);
                $("#Sort").attr("readonly", true);
            }
        });
    }
    //选择角色
    $('#pageList').on('click', 'tr', function () {
        var temp = parseInt($(this).find('td:first').text());
        if (rid == temp)
            return false;
        rid = temp;
        $('.chooseRole').text($(this).find('td').eq(1).text());
        $('.showRoleTitle').text('查看角色 -- '+$(this).find('td').eq(1).text());
        $('.roleType').text($(this).find('td').eq(2).text());
        $('.roleDept').text($(this).find('td').eq(3).text());
        $('.roleCount').text($(this).find('td').eq(4).text());
        $('.roleOrder').text($(this).find('td').eq(5).text());
        $('.roleState').text($(this).find('td').eq(6).text());
        $('#pageList tr').removeClass('check');
        $(this).addClass('check');
        if(!isNaN(rid)){
        	$('#editBtn').removeAttr('disabled');
            $('#deleteBtn').removeAttr('disabled');
            $('#roleUserBtn').removeAttr('disabled');
            $('#roleLimitBtn').removeAttr('disabled');
            $('#examineBtn').removeAttr('disabled');
        }
    });

    //刷新按钮
    $('.btns-container').on('click','#refreshBtn', function () {
        loadList();
        loadPageList(deptId, false);
    });
    
    //获取所有系统按钮
    Y.API2('Button','GetList',{ModuleID:0},function(data){
    	if(data.Success == false){
    		swal(data.Message, '', 'error');
    	}else{
    		if(data.length > 0){
    			var tdList = [];
    			tdList.push({tdText:'模块列表', c:0 , r:0, tdHtml:'', tdId:'', tdClass:''});
    			data.map(function(item){
    				tdList.push({tdText: item.BtnName, c:0 , r:0, tdHtml:'', tdId:'', tdClass:item.ID});
    			});
    			// console.log(data)








    			tableControl.initThead('.moduleHead',[{
    				trClass:'',
    				children:tdList
    			}])
    		}
    	}
    });
    //查看按钮
    $('.btns-container').on('click','#examineBtn', function () {
    	$('#configWindow .tabs-container li:first a').click();
    	$('.roleInfoUsers').empty();
    	layer.msg('玩命加载中……', {icon: 16, shade: 0.5, time:0, maxWidth:200});
        Y.API2('Role', 'GetUserListByRoleId', { RoleID: rid }, function (data) {
        	layer.closeAll('dialog');
            if (data.Success == false) {
                swal(data.Message, '', 'error');
            } else {
                //处理角色信息
                var html = '';
                if(data.userList.length > 0){
                
                	data.userList.map(function(item){
                		html += '<button type="button" style="margin-right:5px;" class="btn btn-'+ (item.Sex == 1 ? 'success' : 'danger') + (btnStyle == 'btn-Style1' ? '' : ' btn-outline') +'">';
                		html += 	'<i class="fa fa-'+ (item.Sex == 1 ? 'mars' : 'venus') +'"></i>&nbsp;&nbsp;' + item.UserName;	
                		html += '</button>';
                	});
                	$('.roleInfoUsers').append(html);
                }else{
                	$('.roleInfoUsers').text('暂无相关用户');
                }
            
                //模块信息
                var tBody = [];
                //   console.log(data.moduleList)  //每条数据  每一行

                // for(var i=0;i<data.moduleList.length;i++){
                //     var BtnName_=0

                //     var html="<tr title='data.moduleList[i]'>"+data.moduleList[i].ModuleName+"</tr>"
                // $(".moduleHead tbody").append(html)

                //     // for(var j=0;j<data.moduleList[i].btnList.length;j++){
                //     //     console.log(data.moduleList[i].btnList[j].BtnName)
                //     //    var htm2=   " <td id='' class='' title='data.moduleList[i].btnList[j].BtnName' style='width: 80px;'>"+data.moduleList[i].btnList[j].BtnName+"</td>"
                //     //      $(".moduleHead tbody tr[title='data.moduleList[i]']").append(htm2)
                //     // }

                // }


                // //   <td id="" class="" title="KM软件平台" style="width: 80px;">KM软件平台</td>
                // // <td id="" class="" title="-" style="width: 21.4359px;">-</td>
                // //   console.log(data)



console.log(data.moduleList)
                data.moduleList.map(function(item,i){
                        console.log()
                	var tdList = [];
                	$('.moduleHead thead th').each(function(index){
                    
                		var $this = $(this);
                		if(index == 0){
                			tdList.push({tdText: item.ModuleName, c:0 , r:0, tdHtml:'', tdId:'', tdClass:''});
                            
                		}else{
                			if(item.Type == 2 && !Y.checkNull(item.btnList) && item.btnList.length > 0){
                				var count = 0;
                				item.btnList.map(function(item2){
                					if(item2.ID == $this.attr('class').trim()){
                						tdList.push({tdText: item2.BtnName, c:0 , r:0, tdHtml:'', tdId:'', tdClass:''});    //这里替换
                						count = -1;	
                					}
                					count++;
                                    //    console.log( item2.BtnName)
                				});
                				if(count == item.btnList.length){
                					// tdList.push({tdText: '-', c:0 , r:0, tdHtml:'', tdId:'', tdClass:''});
                                    return
                				}
                			 }else{
                				// tdList.push({tdText: '-', c:0 , r:0, tdHtml:'', tdId:'', tdClass:''});
                                return
                			}
                          
                		}
                        console.log(tdList)
                          
                	})
          
                    // console.log(item.ModuleName)  //模块权限标题
               
                    
                	var tempTr = {
						trClass: (i % 2 == 0 ? 'gradeX footable-even' : 'gradeX footable-odd' ),
						children: tdList
					};
                	tBody.push(tempTr);
				})
                tableControl.initTbody('.moduleBody',(tBody.length > 0 ? tBody : null), $('.moduleHead thead th').size(),null);
                //样式调整
                var thCount = $('.moduleHead th').size();
              
                // $('.moduleHead th:first').css({width:'120px'});
                // $('.moduleBody tbody tr').each(function(){
                // 	$(this).find('td').each(function(index){
                // 		if(index == 0){
                // 			$(this).css({width:'80px'});
                // 		}else{
                // 			$('.moduleHead th').eq(index).css({width:($('#configWindow .panel-body').width() - 90) / (thCount - 1) + 'px'});
                // 			$(this).css({width:($('#configWindow .panel-body').width() - 90) / (thCount - 1) + 'px'});
                // 		}
                // 	})
                // });
                
            }
        });
    });
    

    //新增按钮
    $('.btns-container').on('click','#addBtn',function () {
        $('.editTitle').text('新增角色');
        isCreate = true;
        $(':input', '#checkModuleForm').not(':button, :submit, :reset').val('');
        $('#RoleType').val();
        loadIndex();
        if (!$('#IsEffective').is(':checked'))
            $('#IsEffective').parent().click();
    });
    //编辑按钮
    $('.btns-container').on('click','#editBtn',function () {
        $('.editTitle').text('编辑角色');
        isCreate = false;
        Y.API2('Role', 'GetID', { RoleID: rid }, function (data) {
            if (data.Success == false) {
                swal(data.Message, '', 'error');
            } else {
                $('#RoleName').val(data.RoleName);
                $('#Sort').val(data.Sort);
                $('#RoleType').val(data.RoleType);
                if ($('#IsEffective').is(':checked') != data.IsEffective) {
                    $('#IsEffective').parent().click();
                }
                $('#Memo').val(data.Memo);
            }
        });
    });

    //点击删除按钮
    commonUtil.initDeleteBtnEvent({
        callBack: function () {
            Y.API2('Role', 'Remove', { RoleID: rid }, function (data) {
                layer.closeAll('dialog');
                if (data.Success == false) {
                    swal('删除失败', data.Message, 'error');
                } else {
                    swal('删除成功', '该信息已被你永久删除', 'success');
                    loadPageList(deptId, true);
                }
            });
        }
    });

    //角色用户按钮
    $('.btns-container').on('click','#roleUserBtn',function () {
        $('#searchText').val('');
        $('#userList .searchList').empty();
        Y.API2('Role', 'GetUsers', { RoleID: rid }, function (data) {
            if (data.Success == false) {
                swal(data.Message, '', 'error');
            } else {
                initRoleList(data);
            }
        });
    });

    //提交角色用户
    $('#saveRoleConfig').click(function () {
//				console.log(roleUserIds);
        Y.API2('Role', 'SetUsers', {
            list: [{ RoleID: rid, UsersID: roleUserIds }]
        }, function (data) {
            if (data.Success == false) {
                swal(data.Message, '', 'error');
            } else {
                swal('保存成功', '', 'success');
                //关闭弹出框
                $('.closeBtn').click();
            }
        });
    })

    //加载模块列表
    var moduleTree = [];
    var moduleList = [];
    var moduleBtns = [];
    Y.API2('Module', 'GetList', {}, function (data) {
        var treeData = {}
        if (!Y.checkNull(data) && data.length > 0) {
            //json处理
            data.map(function (item, i) {
                treeData.text = item.ModuleName;
                treeData.data = {
                    Grade: item.Grade,
                    ID: item.ID,
                    SuperiorModule: item.SuperiorModule,
                    Type: item.Type
                };
                if (item.Childrens.length > 0) {
                    treeData.nodes = getModuleNode(item.Childrens);
                }
            });
            moduleTree.push(treeData);
            $('#moduleList').treeview({
                data: moduleTree,
                showCheckbox: true,
                uncheckedIcon: 'glyphicon glyphicon-unchecked',
            }).on('nodeSelected', function (event, d) {
                //选择节点事件
                $('.chooseModule').text(d.text);
                mid = d.data.ID;
                $('#btnList').empty();
                if (d.data.Type == 2) {
                    loadBtnList(mid);
                }
                $('#moduleList').treeview('checkNode', [d.nodeId]);
            }).on('nodeChecked', function (event, node) {
                //选择提交节点
                var count = 0;
                roleLimitList.map(function (item, i) {
                    if (item == node.data.ID)
                        return false;
                    count++;
                });
                if (count == roleLimitList.length)
                    roleLimitList.push(node.data.ID);
            }).on('nodeUnchecked', function (event, node) {
                //取消选择提交节点
                _.pull(roleLimitList, node.data.ID);
            });
            moduleList = $('#moduleList').treeview('getEnabled');
        }
    });

    //获取模块列表子节点
    var getModuleNode = function (data) {
        var tempArr = [];
        data.map(function (item, i) {
            var temp = {};
            temp.text = item.ModuleName;
            temp.data = {
                Grade: item.Grade,
                ID: item.ID,
                SuperiorModule: item.SuperiorModule,
                Type: item.Type
            };
            if (!Y.checkNull(item.Childrens) && item.Childrens.length > 0) {
                temp.nodes = getModuleNode(item.Childrens);
            }
            tempArr.push(temp);
        });
        return tempArr;
    }
    //获取部门列表子节点
    var getDeptNode = function (data) {
        var tempArr = [];
        data.map(function (item, i) {
            var temp = {};
            temp.text = item.DeptContent;
            temp.data = {
                Grade: item.Grade,
                DeptID: item.DeptID,
                DeptCode: item.DeptCode,
                ParentID: item.ParentID
            };
            if (!Y.checkNull(item.Children) && item.Children.length > 0) {
                temp.nodes = getDeptNode(item.Children);
            }
            tempArr.push(temp);
        });
        return tempArr;
    }

    //角色权限按钮
    $('.btns-container').on('click','#roleLimitBtn',function () {
        //判断是否已存在选中节点
        var isSelect = false;
        layer.msg('玩命加载中……', {icon: 16, shade: 0.5, time:0, maxWidth:200});
        Y.API2('Role', 'GetModules', {
            RoleID: rid
        }, function (data) {
            layer.closeAll('dialog');
            if (data.Success == false) {
                swal(data.Message, '', 'error');
            } else {
                roleLimitList = [];
                tempLimitList = [];
                data.list.map(function (item, i) {
                    roleLimitList.push(item.ModuleID);
                    tempLimitList.push(item);
                });
                $('#moduleList').treeview('uncheckAll', { silent: true });
                moduleList.map(function (item, i) {
                    data.list.map(function (item2, j) {
                        if (item2.ModuleID == item.data.ID) {
                            $('#moduleList').treeview('checkNode', [item.nodeId]);
                            if (!isSelect) {
                                isSelect = true;
                                $('#moduleList').treeview('unselectNode', [item.nodeId, { silent: true }]);
                                $('#moduleList').treeview('selectNode', [item.nodeId]);
                            }
                        }
                    })
                });
            }
        });
    });

    //提交角色权限
    $('#saveModuleConfig').on('click', function () {
        if (roleLimitList.length == 0) {
            swal('至少要选中一个模块');
            return false;
        }

        var tempList = [];
        tempLimitList.map(function (item) {
            roleLimitList.map(function (r) {
                if (r == item.ModuleID)
                    tempList.push(item);
            })
        });

        if (roleLimitList.length > tempList.length) {
            roleLimitList.map(function (item) {
                var count = 0;
                tempList.map(function (item2) {
                    if (item == item2.ModuleID) {
                        return false;
                    }
                    count++;
                });
                if (count == tempList.length) {
                    tempList.push({
                        ModuleID: item,
                        BtnID: []
                    })
                }
            });
        }

        //console.log('tempLimitList',tempLimitList);
        //console.log('roleLimitList',roleLimitList);
        //console.log(tempList);

        layer.msg('玩命加载中……', {icon: 16, shade: 0.5, time:0, maxWidth:200});
        Y.API2('Role', 'SetModules', {
            RoleID: rid,
            list: tempList
        }, function (data) {
            layer.closeAll('dialog');
            if (data.Success == false) {
                swal(data.Message, '', 'error');
            } else {
                swal('保存成功', '', 'success');
                //关闭弹出框
                $('.closeBtn').click();
            }
        });
    });

	//检验提交信息
	$('#addModuleBtn').click(function(){
		if (!CheckDataValid('#checkModuleForm')) {
            return false;
        }
		//检验通过后执行新增或者编辑
        var deal = '';
        var successText = '';
        if (isCreate) {
            deal = 'Create';
            successText = '新增成功';
        } else {
            deal = 'Modify';
            successText = '编辑成功';
        }
        layer.msg('玩命加载中……', {icon: 16, shade: 0.5, time:0, maxWidth:200});
        Y.API2('Role', deal, {
            ID: rid,
            RoleName: $('#RoleName').val(),
            RoleType: $('#RoleType').val(),
            Sort: $('#Sort').val(),
            IsEffective: $('#IsEffective').is(':checked'),
            Memo: $('#Memo').val(),
            DeptID: deptId
        }, function (data) {
            layer.closeAll('dialog');
            if (data.Success == false) {
                swal(data.Message, '', 'error');
            } else {
                swal(successText, '', 'success');
                //关闭新建  or 编辑框
                $('#closeAddBox').click();
                //刷新列表
                loadPageList(deptId, true);
            }
        })
	})
});
</script>
</asp:Content>